import { AxiosResponse, InternalAxiosRequestConfig } from './types'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import { SUCCESS_CODE, TRANSFORM_REQUEST_DATA } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { objToFormData } from '@/utils'

const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  if (
    config.method === 'post' &&
    config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
  ) {
    config.data = qs.stringify(config.data)
  } else if (
    TRANSFORM_REQUEST_DATA &&
    config.method === 'post' &&
    config.headers['Content-Type'] === 'multipart/form-data' &&
    !(config.data instanceof FormData)
  ) {
    config.data = objToFormData(config.data)
  }
  if (config.method === 'get' && config.params) {
    let url = config.url as string
    url += '?'
    const keys = Object.keys(config.params)
    for (const key of keys) {
      if (config.params[key] !== void 0 && config.params[key] !== null) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
    }
    url = url.substring(0, url.length - 1)
    config.params = {}
    config.url = url
  }
  return config
}

const defaultResponseInterceptors = (response: AxiosResponse) => {
  // 调试日志
  console.log(`[API响应][${response.config.url}]`, response)

  // 如果是文件流，直接返回
  if (response?.config?.responseType === 'blob') {
    return response
  }

  // 检查是否有响应数据
  if (!response || !response.data) {
    console.warn(`[API响应][${response?.config?.url}] 响应无数据`)
    return response // 返回原始响应，让业务层处理
  }

  // 检查响应状态码
  if (response.data.code === SUCCESS_CODE) {
    return response.data
  } else {
    // 处理业务错误
    const errorMessage =
      response.data.message || response.data.msg || `错误码: ${response.data.code || '未知'}`
    // console.error(`[API响应][${response.config.url}] 业务错误:`, errorMessage)

    // 未授权处理
    if (response.data.code === 401) {
      ElMessage.error('登录已过期，请重新登录')
      const userStore = useUserStoreWithOut()
      userStore.logout()
      return Promise.reject(new Error(errorMessage))
    }

    // 其他业务错误
    // ElMessage.error(errorMessage)
    return response.data // 返回数据，让业务层处理状态码
  }
}

export { defaultResponseInterceptors, defaultRequestInterceptors }
